<?php

namespace App\Services\Setting;

use App\Constants\CodeData;
use App\Dao\AnchorDao;
use App\Dao\AppUpgradeDao;
use App\Dao\CommonSettingDao;
use App\Exception\MessageException;
use App\Model\Anchor;
use App\Model\TeenMode;
use App\Model\User;
use App\Model\UserSetting;
use App\Utils\MemcacheClient;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use function Hyperf\Config\config;

class SettingService
{

    /**
     * 当前等级，下一级，当等级值和下一级值的差，当前等级值到下一等级值完成的百分比
     * @param array $param
     * @return array
     */
    public function getWealth()
    {
        $user = Context::get('user');
        $uid = $user['id'];
        $data = User::query()->select('wealth', 'nickname', 'head_image')->find($uid);
        [$level1, $level2, $diff, $percent] = getWealthLevelEx($data['wealth']);
        return formatData([
            'result' => 1,
            'msg' => [
                'wealth' => $data['wealth'],
                'nickname' => $data['nickname'],
                'head_image' => $data['head_image'],
                'level1' => $level1,
                'level2' => $level2,
                'diff' => $diff,
                'percent' => $percent,
            ]

        ]);
    }


    /**
     * Note - 我的设置页面信息
     * DateTime 2024/8/7 19:27
     * User Admin
     * @param array $params
     * @return array
     */
    public function mySetting(array $params)
    {
        $userInfo = Context::get('user');
        $uid = $userInfo['id'];
        $anchorModel = new AnchorDao();
        $anchor = $anchorModel->findAnchorInfoById($uid);
        $teenModeNoExits = TeenMode::query()->where('uid', $uid)->where('status', 1)->doesntExist();
        $userSetting = UserSetting::query()->where('uid', $uid)->first(['show_addr', 'hidden_nick']);
        if ($userSetting && $userSetting['show_addr'] >= 0) {
            $show_addr = $userSetting['show_addr'];
        } else {
            $show_addr = ($userInfo['sex'] == 1) ? '1' : '0';
        }

        $data = [
            'hidden_nick' => $userSetting['hidden_nick'],// 电视墙是否匿名：0-不匿名，1-匿名
            'show_addr' => $show_addr,    // 位置展示开关
            'is_disturb' => $userInfo['is_disturb'],      //是否开启勿扰
            'show_gift' => $userInfo['show_gift'],      //是否显示礼物
            'show_wealth' => $userInfo['show_wealth'],      //是否展示财富榜
            'show_online' => $userInfo['show_online'],      //是否开启上线通知
            'accept_video' => $userInfo['accept_video'] ?? '0',    //接受视频匹配
            'accept_audio' => $userInfo['accept_audio'] ?? '0',    //接受语音匹配
            'hide_call_status' => $userInfo['hide_call_status'] ?? '0',    //是否隐藏通话状态
            'video_price' => intval($anchor['video_price'] ?? 0),      //视频价格
            'audio_price' => 600,      //语音价格
            'auto_reply_status' => $anchor['auto_reply_status'] ?? '0',  //托管
            'teen_mode' => $teenModeNoExits ? '0' : '1',     //青少年模式
            'agreement' => HOST . "/app/h5/yliao/xieyi.html",  //用户协议
            'specification' => HOST . "/app/h5/yliao/gf.html",  //平台行为规范
            'privacy' => HOST . "/app/h5/yliao/zc.html",  //隐私政策
            'close_account_num' => CommonSettingDao::getValue("can_close_account_num"),    // 可注销账号次数
            'show_report' => CommonSettingDao::getValue($userInfo['sex'] == 1 ? "man_show_report" : "woman_show_report"),    // 是否显示举报记录
        ];

        $appUpgrade = new AppUpgradeDao();
        if ($appUpgrade->isHideCall($params["from"], $params["version_code"], $params['channel'])) {
            $data['agreement'] = HOST . "/app/h5/yliao/xieyi_check.html";  //用户协议
            $data['specification'] = HOST . "/app/h5/yliao/gf_check.html";  //平台行为规范
            $data['privacy'] = HOST . "/app/h5/yliao/zc_check.html";  //隐私政策
        }

        if ($params['package'] == "com.claw.planet") {
            // (2022-07-04 爪爪换成约伴)
            $data['agreement'] = HOST . "/app/h5/yueban/xieyi.html";  //用户协议
            $data['specification'] = HOST . "/app/h5/yueban/gf.html";  //平台行为规范
            $data['privacy'] = HOST . "/app/h5/yueban/zc.html";  //隐私政策

            if ($appUpgrade->isHideCall($params["from"], $params["version_code"], $params['channel'])) {
                $data['agreement'] = HOST . "/app/h5/yueban/xieyi_check.html";  //用户协议
                $data['specification'] = HOST . "/app/h5/yueban/gf_check.html";  //平台行为规范
                $data['privacy'] = HOST . "/app/h5/yueban/zc_check.html";  //隐私政策
            }
        }
        return formatData(array('result' => 1, 'msg' => $data));
    }


    /**
     * Note - 获取价格
     * DateTime 2024/8/12 17:39
     * User Admin
     */
    public function getPrice($userInfo)
    {
        $uid = $userInfo['id'];
        if ($userInfo['sex'] != 2) {
            throw new MessageException('用户不支持该设置');
        }
        $anchor = Anchor::query()->where('uid', $uid)->select([Db::raw('greet_price as text_price'), 'uid', 'video_price', 'audio_price'])->first();
        $anchor = modelToArray($anchor);
        $wealth = User::query()->where('id', $uid)->value('wealth');
        $level = max(getWealthLevel($wealth), 20);

        // 视频价格
        $videoPrices = config('custom.video_prices');
        foreach ($videoPrices as &$item) {
            if ($item['level'] <= $level) {
                $item['choose'] = 1; // 0-不可选，1-可选
            }
            if ($anchor['video_price'] == $item['gold']) {
                $item['is_choose'] = 1; // 1-选中，0-未选中
            }
        }

        // 音频价格
        $audioPrices = config('custom.audio_prices');
        foreach ($audioPrices as &$item1) {
            if ($item1['level'] <= $level) {
                $item1['choose'] = 1;
            }
            if ($anchor['audio_price'] == $item1['gold']) {
                $item1['is_choose'] = 1;
            }
        }

        // 聊天价格 choose:0-不可选，1-可选；is_choose:0-未选中，1-选中
        $textPrices = config('custom.text_prices');
        foreach ($textPrices as &$item2) {
            if ($item2['level'] <= $level) {
                $item2['choose'] = 1;
            }
            if ($anchor['text_price'] == $item2['gold']) {
                $item2['is_choose'] = 1;
            }
        }

        return formatData(array('msg' => [
            'anchor' => $anchor,
            'videoPrices' => $videoPrices,
            'audioPrices' => $audioPrices,
            'textPrices' => $textPrices,
        ], 'result' => 1));
    }


    /**
     * Note - 通话设置（设置价格）
     * DateTime 2024/8/12 17:52
     * User Admin
     * @param mixed $userInfo
     * @param $params
     */
    public function setPrice(mixed $userInfo, $params)
    {
        $uid = $userInfo['id'];
        $type = $params['type'] ?? 1;    // 1视频价格 2语音价格 3聊天消息价格
        $gold_price = $params['gold_price'] ?? 0;    // 金币价格
        $language = $params['language'];

        // 视频价格
        $videoPrices = config('custom.video_prices');
        // 音频价格
        $audioPrices = config('custom.audio_prices');
        // 聊天价格
        $textPrices = config('custom.text_prices');

        if ($userInfo['sex'] != 2) {
            throw new MessageException('用户不支持该设置');
        }
        $wealth = User::query()->where('id', $uid)->value('wealth');
        $level = max(getWealthLevel($wealth), 20);
        switch ($type) {
            case 1:
                $price = array_column($videoPrices, "level", 'gold');
                $updateField = 'video_price';
                break;
            case 2:
                $price = array_column($audioPrices, "level", 'gold');
                $updateField = 'audio_price';
                break;
            case 3:
                $price = array_column($textPrices, "level", 'gold');
                $updateField = 'greet_price';
                break;
            default:
                exit;
        }
        if (!isset($price[$gold_price])) {
            throw new MessageException('价格设置错误', 200, CodeData::NEED_TIPS);
        }
        if ($price[$gold_price] > $level) {
            throw new MessageException('你不能设置该价格', 200, CodeData::NEED_TIPS);
        }
        $res = Anchor::query()->where('uid', $uid)->update([$updateField => $gold_price]);
        if ($res) {
            MemcacheClient::getInstance()->delete('user_detail_info_' . $language . $uid);
            return formatData(array('msg' => ['result' => 1, 'msg' => $res], 'result' => 1));
        } else {
            throw new MessageException('修改失败', CodeData::NEED_TIPS);
        }
    }

    /**
     * Note - 语言设置
     * DateTime 2024/8/12 17:52
     * User Admin
     * @param array $params
     */
    public function changeLanguage($userInfo, $language)
    {
        $uid = $userInfo['id'];
        $userInfo['ext2']->language = $language;
        $update['ext2'] = json_encode($userInfo['ext2']);
        User::query()->where('id', $uid)->update($update);
    }


    public function acceptVideo($uid, $params)
    {
        $type = $params['type'];// 1开启 0关闭
        $accept_type = $params['accept_type'];
        $field = $accept_type ? 'accept_audio' : 'accept_video';
        // $res = (new UserModel())->updateByWhere([$field => $type], "id={$uid}");
        $res = User::query()->where('id', $uid)->update([$field => $type]);

        if (!$res) {
            // Tool::JSON(\CodeData::NEED_TIPS, array('result' => 0), '操作失败');
            return formatData(['result' => 0], 200, CodeData::NEED_TIPS, '操作失败');
        }
        MemcacheClient::getInstance()->delete("userInfo_" . $uid);
        return formatData(['result' => 1]);
        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1), '操作成功');
    }


    public function setHideNickname(mixed $uid, mixed $status)
    {
        return UserSetting::query()->updateOrInsert(['uid' => $uid], ['hidden_nick' => $status]);
    }

}